import Config from '@/utils/Config'
import { Base64 } from 'js-base64'
import { getToken } from '@/store/Store'
import { useSystemStore } from '@/store/modules/system'

// 加载提示
function $showLoading () {
  uni.showLoading({
    title: '加载中',
    mask: true
  })
  setTimeout(() => {
    uni.hideLoading();
  }, 10000);
}
function $showTokenLoading () {
  uni.showLoading({
    title: '安全验证中...',
    mask: true
  })
  setTimeout(() => {
    uni.hideLoading();
  }, 15000);
}
function $closeLoading () {
  uni.hideLoading()
}

// 初始化配置
function $config (config) {
  if (typeof (config.loading) === 'undefined') config.loading = true
  if (typeof (config.tips) === 'undefined') config.tips = true
}

/**
 * 请求前 Token 处理（简化对象属性写法）
 */
function $request (params) {
  const token = getToken()
  const config = params.config || {}
  $config(config)
  // 合并 header 时使用展开语法（更清晰）
  const header = { ...params.header }
  params = { ...params, header, config }

  // 加载提示逻辑
  if (config.loading && !params.url.endsWith('token')) {
    $showLoading()
  } else if (config.loading) {
    $showTokenLoading()
  }

  // Token 注入逻辑
  if (params.url.endsWith('token')) {
    header.Authorization = `Basic ${Base64.encode(`${Config.clientId}:${Config.clientSecret}`)}`
  } else if (token) {
    header.Authorization = token
  }

  return request(params)
}

/**
 * 真正的请求（简化结构）
 */
function request (params) {
  return new Promise((resolve, reject) => {
    const { config, method = 'GET', url, header } = params
    config.method = method
    const _params = {
      url: Config.baseRequestUrl + url,
      method,
      header,
      fail: err => errorHandle(reject, err.message || '非法请求', config)
    }

    // 区分上传/下载/普通请求
    if (method === 'UPLOAD') {
      const { path, name, formData, files, file } = params
      delete _params.method
      _params.filePath = path
      _params.name = name
      _params.files = files
      _params.file = file
      _params.formData = formData
      _params.success = ({ statusCode, data }) => successHandle({ resolve, reject, data, statusCode, config })
      uni.uploadFile(_params)
    } else if (method === 'DOWNLOAD') {
      _params.success = ({ tempFilePath, statusCode }) => successHandle({
        resolve, reject, tempFilePath, statusCode, config
      })
      uni.downloadFile(_params)
    } else {
      const { data, dataType, responseType } = params
      _params.data = data
      _params.dataType = dataType
      _params.responseType = responseType
      _params.success = ({ data, statusCode, header }) => successHandle({
        resolve, reject, data, statusCode, header, config
      })
      uni.request(_params)
    }
  })
}

/**
 * 请求成功回调（简化变量解构）
 */
function successHandle ({ resolve, statusCode, config, data, tempFilePath, header }) {
  config.loading && $closeLoading()

  if (statusCode === 200) {
    const { method } = config
    if (method === 'DOWNLOAD') {
      resolve(tempFilePath)
    } else {
      // 上传场景解析 data
      if (method === 'UPLOAD' && data) data = JSON.parse(data)

      // 业务状态码处理
      if (data.code === 200) {
        resolve(data.data, header)
      } else if (data.code === 401) {
        this.systemLogout()
        uni.navigateTo({ url: '/pages/index/login' })
      } else {
        resolve(data, header)
      }
    }
  } else if (statusCode === 401) {
    // 网络状态检查
    uni.getNetworkType({
      success: function (res) {
        console.log(res.networkType);// 网络类型 wifi、2g、3g、4g、ethernet、unknown、none
        if (res.networkType === 'none') {
          console.log('当前无网络');
        } else {
          this.systemLogout()
          uni.navigateTo({ url: '/pages/index/login' })
        }
      }
    });
  } else if (statusCode === 400) {
    uni.showToast({ icon: 'none', title: data.error_description })
  } else {
    uni.showToast({ icon: 'none', title: data.msg })
  }
}

// 错误处理
function errorHandle (reject, msg, config) {
  uni.getNetworkType({
    success: function (res) {
      console.log(res.networkType);// 网络类型 wifi、2g、3g、4g、ethernet、unknown、none
      if (res.networkType === 'none') {
        console.log('当前无网络');
      } else {
        this.systemLogout()
        uni.reLaunch({ url: '/pages/index/login' })
      }
    }
  });
}

// 导出方法（简化对象属性写法）
export const get = ({ url, params = {}, config = {}, header }) => $request({
  url, method: 'GET', data: params, header,
  dataType: config.dataType, responseType: config.responseType, config
})

export const post = ({ url, params = {}, config = {}, header }) => $request({
  url, method: 'POST', data: params, header,
  dataType: config.dataType, responseType: config.responseType, config
})

export const upload = ({ url, params = {}, config = {}, header }) => $request({
  url, method: 'UPLOAD',
  path: params.path, name: params.name, files: params.files, file: params.file, formData: params.formData,
  header, config
})

export const download = ({ url, config = {}, header }) => $request({
  url, method: 'DOWNLOAD', header, config
})

export function systemLogout() {
  // ✅ 通过 getCurrentInstance 安全访问 store
  const instance = getCurrentInstance()
  if (!instance) return false

  const systemStore = useSystemStore()
  systemStore.logout()
}
